from base.web import SHandler, BaseHandler, get_files
import hashlib
from api.product import domin
class set_config(SHandler):
    def post(self):
        has = self.query_sql('select count(*) as has from pj_config;')[0]['has']
        config_list = ['adaccount', 'adpwd', 'address', 'connect_name_1', 'connect_name_2', 'connect_phone_1', 'connect_phone_2', 'name']
        params = []
        has_config_list = []
        for key in config_list:
            if self.get_argument(key, False):
                if has:
                    params.append(key + '=' + '\'' + self.get_argument(key, '') + '\'')
                else:
                    params.append('\'' + self.get_argument(key, '') + '\'')
                    has_config_list.append(key)
        if has:
            if self.modify_sql('update pj_config set {params}'.format(params = ','.join(params))):
                res = self.res_success('modify')
            else:
                res = self.res_error('modify')
        else:
            print('insert into pj_config ({keys}) values ({values})'.format(keys = ','.join(has_config_list),values = ','.join(params)))
            if self.insert_sql('insert into pj_config ({keys}) values ({values});'.format(keys = ','.join(has_config_list),values = ','.join(params))):
                res = self.res_success('modify')
            else:
                res = self.res_error('modify')
        self.write(res)

class modify_pwd(SHandler):
    def post(self):
        h = hashlib.sha256()
        h.update(bytes(self.get_argument('oldpwd', ''), encoding='utf-8'))
        oldpwd = h.hexdigest()
        h = hashlib.sha256()
        h.update(bytes(self.get_argument('newpwd', ''), encoding='utf-8'))
        newpwd = '\'' + h.hexdigest() + '\''
        config = self.query_sql('select adpwd from pj_config where id = 1')[0]
        print(oldpwd)
        print(newpwd)
        if config['adpwd'] == oldpwd:
            if self.modify_sql('update pj_config set adpwd = {0} where id = 1'.format(newpwd)):
                res = self.res_success('modify')
            else:
                res = self.res_error('modify')
        else:
            res = dict(
                code = 1,
                message = '旧密码错误'
            )
        self.write(res)
class config_detail(BaseHandler):
    def post(self):
        query_list = ['address', 'connect_name_1', 'connect_name_2', 'connect_phone_1', 'connect_phone_2', 'name']
        config = self.query_sql('select count(*) as has, {keys} from pj_config where id = 1;'.format(keys = ','.join(query_list)))[0]
        if config['has']:
            res = self.res_success('query', object=config)
        else:
            object = {}
            for key in query_list:
                object[key] = ''
            res = self.res_success('query', object=object)
        self.write(res)

class create_content(SHandler):
    def post(self):
        create_list = ['name', 'remark', 'level']
        params = []
        for key in create_list:
            if key == 'level':
                params.append(self.get_argument(key, ''))
            else:
                params.append('\'' + self.get_argument(key, '') + '\'')
        if self.request.files:
            filesList = get_files(self.request.files)['data']
            params.append('\'' + ','.join(filesList) + '\'')
        params = ','.join(params)
        if self.insert_sql('insert into pj_content ({keys},img) values ({values});'.format(keys = ','.join(create_list), values=params)):
            res = self.res_success('insert')
        else:
            res = self.res_error('insert')
        self.write(res)

class query_content(BaseHandler):
    def post(self):
        try:
            data = self.query_sql('select * from pj_content where isdel = 0')
            res = self.res_success('query', data, {'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)
    
class content_detail(SHandler):
    def post(self):
        try:
            content = self.query_sql('select * from pj_content where id = {id}'.format(id = int(self.get_argument('id', ''))))
            res = self.res_success('query', object={'content': content[0], 'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)

class del_content(SHandler):
    def post(self):
        if self.modify_sql('update pj_content set isdel = {0} where id = {1}'.format(self.get_argument('isdel', 0), self.get_argument('id', ''))):
            self.modify_sql('update pj_product set isdel = {0} where contentid = {1}'.format(self.get_argument('isdel', 0), self.get_argument('id', '')))
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class modify_content(SHandler):
    def post(self):
        modify_list = ['name', 'remark', 'level']
        params = []
        savelist = []
        filesList = []
        for key in modify_list:
            value = self.get_argument(key, '')
            if value or (value == 0):
                if key == 'level':
                    params.append(key + '=' + value)
                else:
                    params.append(key + '=' + '\'' + value + '\'')
        
        if self.request.files:
            filesList = get_files(self.request.files)['data']
        if self.get_argument('img', ''):
            savelist = filesList + self.get_argument('img', '').split(',')
        else:
            savelist = filesList
        params.append('img=' + '\'' + ','.join(savelist) + '\'')
        params = ','.join(params)
        print('update pj_content set {0} where id = {1}'.format(params, self.get_argument('id', '')))
        if self.modify_sql('update pj_content set {0} where id = {1}'.format(params, self.get_argument('id', ''))):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class islogin(SHandler):
    def post(self):
        self.write(
            dict(
                code = 0,
                message = '已登陆'
            )
        )

config_url = [
    #修改配置
    (r"/api/config/set_config", set_config),
    #配置详情
    (r"/api/config/config_detail", config_detail),
    #添加业务
    (r"/api/config/create_content", create_content),
    #查询业务
    (r"/api/config/query_content", query_content),
    #业务详情  
    (r"/api/config/content_detail", content_detail),
    #业务删除
    (r"/api/config/del_content", del_content),
    #修改业务
    (r"/api/config/modify_content", modify_content),
    # 修改密码
    (r"/api/config/modify_pwd", modify_pwd),
    # 检测是否登陆
    (r"/api/config/islogin", islogin),
]